<template>
	<div class="interaction">
		<el-row>
			<el-col :span="8" style="margin-top: 5px; color: white">事件类型</el-col>
			<el-col :span="16">
				<el-select
					v-model="state.event"
					name="event"
					style="width: 100%"
					@change="handleEventChange">
					<el-option
						v-for="event in state.events"
						:key="event.value"
						:label="event.name"
						:value="event.value"></el-option>
				</el-select>
			</el-col>
		</el-row>
		<el-row style="margin: 10px 0">
			<el-col :span="8" style="margin-top: 5px; color: white">组件</el-col>
			<el-col :span="16">
				<el-row>
					<el-col :spam="24">
						<!-- <SelectTree
							v-if="true"
							:props="state.defaultProps"
							:multiple="true"
							placeholder="请选择响应组件"
							nodeKey="uuid"
							v-model="state.actionCpnt"
							:data="appCpntTree"
							clearable
							style="width: 100%"
							:check-strictly="true"
							@select-change="handleTreeChange"></SelectTree> -->
						<el-tree-select
							v-model="state.actionCpnt"
							:data="appCpntTree"
							multiple
							placeholder="请选择响应组件"
							:render-after-expand="false"
							:props="{ label: 'name' }"
							node-key="uuid"
							check-strictly
							check-on-click-node
							@node-click="handleTreeClick"
							@change="handleTreeChange" />
					</el-col>
				</el-row>
			</el-col>
		</el-row>
		<el-row>
			<el-col :span="8" style="margin-top: 5px; color: white">动作</el-col>
			<el-col :span="16">
				<el-select
					v-model="state.actionValue"
					name="action"
					style="width: 100%; margin-bottom: 10px"
					@change="handleActionChange">
					<el-option
						v-for="action in state.actions"
						:key="action.value"
						:label="action.name"
						:value="action.value"></el-option>
				</el-select>
			</el-col>
		</el-row>
		<component
			v-for="(cpnt, index) in state.actionConfiguration"
			:is="cpnt.type.replace(/( |^)[a-z]/, (L: any) => L.toUpperCase())"
			:key="cpnt.type + index"
			:data="cpnt"
			:ref="cpnt.type + index"
			@handleValueChange="handleValueChange" />
	</div>
</template>

<script lang="ts" setup>
import { onMounted, reactive, ref, toRefs, provide } from 'vue';
import _ from 'lodash';
import { RUNTIME_CFG_ENUM } from '@CIF/Runtime/Global/variable';
import StorageHelper from '@CIF/Runtime/Global/storage';
import { ComponentTreeHelper } from '@CIF/ComponentTemplate/componentTree';
import { reduceConfig, increaseConfig, findConfigDataByValue } from '@CIF/Utils/reduce-config';
import { usePrimaryStore } from '@/store';

const store = usePrimaryStore();
const props = defineProps({
	instance: {
		type: Object,
		default() {
			return {};
		}
	},
	interaction: {
		type: Object,
		default() {
			return {};
		}
	}
});

const interaction = ref(props.interaction);
const appCpntTree = StorageHelper.get(RUNTIME_CFG_ENUM.APPLICATION_COMPONENT_TREE);
const validActionCpnt =
	interaction.value?.cpntIds &&
	interaction.value.cpntIds.filter(
		(x: any) => !!ComponentTreeHelper.findTreeNodeDetail(appCpntTree, x).cpntTreeNode
	);
const state: any = reactive({
	events: props.instance.definitionRefrence.events,
	event: interaction.value.event || '',
	actions: [],
	actionValue: interaction.value.action || '',
	actionConfiguration: [],
	actionCacheConfiguration: {},
	cpntName: interaction.value.cpntNames || '',
	defaultProps: {
		label: 'name'
	},
	appCpntTree: appCpntTree,

	actionCpnt: validActionCpnt || [],

	treeData: [
		{
			label: '新疆维吾尔自治区',
			id: '1',
			childrens: [
				{
					label: '乌鲁木齐市',
					id: '2',
					childrens: [
						{ label: '达坂城区', id: '7', childrens: [] },
						{ label: '头屯河区', id: '8', childrens: [] },
						{ label: '乌鲁木齐县', id: '9', childrens: [] }
					]
				},
				{
					label: '克拉玛依市',
					id: '3',
					disabled: true,
					childrens: [
						{
							label: '克拉玛依区',
							id: '10',
							disabled: true,
							childrens: []
						},
						{ label: '白碱滩区', id: '11', disabled: true, childrens: [] },
						{ label: '独山子区', id: '12', disabled: true, childrens: [] }
					]
				},
				{ label: '吐鲁番地区', id: '4', childrens: [] },
				{ label: '哈密地区', id: '5', childrens: [] },
				{ label: '昌吉回族自治州', id: '6', childrens: [] }
			]
		}
	],
	treeProps: {
		value: 'id',
		children: 'childrens',
		label: 'label'
	}
});

function handleEventChange() {
	// 将事件类型保存起来
	interaction.value.event = state.event;
}

function isActionsEqual(x: any, y: any) {
	if (!_.isEqual(_.get(x, 'value'), _.get(y, 'value'))) {
		return false;
	} else {
		if (!_.isEqual(_.get(x, 'config'), _.get(y, 'config'))) {
			return false;
		} else {
			return true;
		}
	}
}

let selectedCpntTreeNodeArr: any = [];
function handleTreeClick(node: any) {
	selectedCpntTreeNodeArr.push(node);
	// console.log('333selectedCpntTreeNodeArr', selectedCpntTreeNodeArr);
}
function handleTreeChange(uuids: any) {
	const idSet = new Set(uuids);
	selectedCpntTreeNodeArr = selectedCpntTreeNodeArr.filter((item: any) => {
		return idSet.has(item.uuid);
	});
	if (_.get(window, 'cif.config.logger.enable', false) === true) {
		console.log(
			'CIF.CC.CIM.C.Interaction:handleTreeChange',
			'selectedCpntTreeNodeArr',
			selectedCpntTreeNodeArr
			// state.actionCpnt
		);
	}
	// 将组件的actions反馈到动作下拉框以做选择
	const actionsArr = selectedCpntTreeNodeArr.map((x: any) =>
		_.get(x, 'componentInstance.definitionRefrence.actions')
	);
	state.actions = _.intersectionWith(...actionsArr, (x: any, y: any) => isActionsEqual(x, y));

	// 针对选中的treenode，反馈组件名称
	// this.cpntName = selectedCpntTreeNodeArr.map(x => _.get(x, "componentInstance.name"))
	// 初始化action相关数据
	(state.actionValue = ''), (state.actionConfiguration = []);
	state.actionCacheConfiguration = {};
	// 将组件uuid和name保存起来
	interaction.value.cpntIds = state.actionCpnt;
	// this.ac
	interaction.value.cpntNames = selectedCpntTreeNodeArr.map((x: any) =>
		_.get(x, 'componentInstance.name')
	);
}

function handleActionChange() {
	// 改变动作内容会考虑两种情况：
	// 1.原有的action就存有配置
	if (state.actionCacheConfiguration[state.actionValue]) {
		state.actionConfiguration = state.actionCacheConfiguration[state.actionValue];
	} else {
		// 2.新建新的action配置
		let action = findConfigDataByValue(state.actions, state.actionValue);
		state.actionConfiguration = _.cloneDeep(action.config);
		// 缓存一份最新的配置信息
		state.actionCacheConfiguration[state.actionValue] = state.actionConfiguration;
	}
	// 将组件action保存起来
	interaction.value.action = state.actionValue;
}

function handleValueChange() {
	if (_.get(window, 'cif.config.logger.enable', false) === true) {
		console.log(
			'CIF.CC.CIM.C.Interaction:handleValueChange 检测到值变动',
			reduceConfig(state.actionConfiguration)
		);
	}
	// 将组件config信息保存起来
	interaction.value.actionConfig = reduceConfig(state.actionConfiguration);
}

onMounted(() => {
	console.log('222222222props.instance', props.instance);
});
defineExpose({ ...toRefs(state) });
// provide('configuration', state.configuration);
</script>

<style lang="scss" scoped>
.cif-input {
	display: flex;
	margin-bottom: 10px;
	&-label {
		display: inline-block;
		overflow: hidden;
		line-height: 40px;
		white-space: nowrap;
		text-align: right;
		vertical-align: middle;
		margin-right: 10px;
		color: var(--white);
	}
	&-wrapper {
		flex: 1;
	}
}
</style>
